package com.jeeplus.modules.web.task;

import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.SpringContextHolder;
import com.jeeplus.common.utils.time.DateUtil;
import com.jeeplus.modules.monitor.utils.Achieve;
import com.jeeplus.modules.web.entity.*;
import com.jeeplus.modules.web.mapper.*;
import com.jeeplus.modules.web.service.WxAgentsRecordingService;
import com.jeeplus.modules.web.service.WxUserWalletService;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author rongjie
 * @version 2.0
 * @data 2017/4/6
 * @E-mail rongjie1357@163.com
 */
@Service
@Lazy(false)
@Component
public class TimersTask implements ImTaskService {

	public static Logger logs = LoggerFactory.getLogger(TimersTask.class);

	/**
	 * task启动早于spring的加载，注解获取实例的方式将不生效，故用SpringContextHolder手动获取实例
	 */
	// @Resource
	// WxEquipment wxEquipment;
	private YjEquipmentMapper yjEquipmentMapper = (YjEquipmentMapper) SpringContextHolder
			.getBean(YjEquipmentMapper.class); // 获取dao 接口 防止注入失败
	private WxOrderMapper wxOrderMapper = (WxOrderMapper) SpringContextHolder.getBean(WxOrderMapper.class); // 获取dao
																											// 接口
																											// 防止注入失败
	private WxUserWalletService wxUserWalletService = (WxUserWalletService) SpringContextHolder
			.getBean(WxUserWalletService.class); // 获取dao 接口 防止注入失败
	private WxUserIntegrationRecordMapper wxUserIntegrationRecordMapper = (WxUserIntegrationRecordMapper) SpringContextHolder
			.getBean(WxUserIntegrationRecordMapper.class); // 获取dao 接口 防止注入失败
																												// 防止注入失败

	private WxAgentsRecordingService wxAgentsRecordingService = (WxAgentsRecordingService) SpringContextHolder
			.getBean(WxAgentsRecordingService.class); // 获取Service 接口 防止注入失败

	int i = 0;

//	@Scheduled(cron = "1/10 * * * * ? ") // 每十秒运行一次
	public void task() {

		if (i == 0) {
			new Server().start();
		}
		i++;
	}

	long ti = (1000l * 24 * 60 * 60);

	/***
	 * 商家利益分成
	 */
	//@Scheduled(cron = "0 0 0 * * ? ") // 每十秒运行一次
	public void distributionTask() {
		List<YjAgentsDistribution> list = yjEquipmentMapper.getYjAgentsDistributionList();
		for (YjAgentsDistribution yjAgentsDistribution : list) {
			long l = System.currentTimeMillis() - yjAgentsDistribution.getTime().getTime();
			if (l < ti) {
				// 分销比例
				String a = yjAgentsDistribution.getAgentsDistributionA();
				String b = yjAgentsDistribution.getAgentsDistributionB();
				String c = yjAgentsDistribution.getAgentsDistributionC();
				yjEquipmentMapper.setDistribution(yjAgentsDistribution.getAgents().getId(), a);

				yjEquipmentMapper.setYjAgentsDistribution(yjAgentsDistribution.getId(), b, c, new Date());
			}
		}
	}

	/***
	 * 检索未开机退款
	 */
	@Scheduled(cron = "0 0/2 * * * ? ") // 每2分钟运行一次
	public void getRefunds() {
		List<WxOrder> list = wxOrderMapper.getRefunds();
		for (WxOrder wxOrder : list) {
			// 超过2分钟未反馈，视为开机成功
			// 判断是否离开机时间有2分钟
			logs.info("System.currentTimeMillis()=" + System.currentTimeMillis());
			logs.info("wxOrder.getTime().getTime()=" + wxOrder.getTime().getTime());
			if (System.currentTimeMillis() > wxOrder.getTime().getTime() + (1000L * 60*2)) {
				//获取设备订单状态
				YjEquipment yjEquipment = yjEquipmentMapper.findUniqueByProperty("number", wxOrder.getEquipmentNumber());
				//判断是否运行中
				List<WxOrder> wxOrderList = wxOrderMapper.getOrderByStatus(wxOrder.getEquipmentNumber(), 2).stream().filter(o -> !o.getOrderNumber().equals(wxOrder.getOrderNumber())).collect(Collectors.toList());
				Integer orderTime = Integer.parseInt(wxOrder.getOrderTime());
				orderTime = orderTime == null ? 60 : orderTime;
				if(wxOrderList.size() > 0 && yjEquipment.getEndTime()!=null){
					//代表有订单运行中，修改结束时间
					long endTime = yjEquipment.getEndTime().getTime()+ orderTime*60*1000;
					yjEquipment.setEndTime(new Date(endTime));
					yjEquipment.setOrders(yjEquipment.getOrders()+","+wxOrder.getId());
				}else{
					//没有订单运行说明是第一个订单，修改开始时间和结束时间
					yjEquipment.setStartTime(wxOrder.getTime());
					yjEquipment.setEndTime(wxOrder.getEndTime());
					yjEquipment.setOrders(wxOrder.getId());
				}

				yjEquipmentMapper.setTotal(wxOrder.getEquipment().getNumber(), orderTime,yjEquipment.getStartTime(),yjEquipment.getEndTime(),yjEquipment.getOrders());// 更新yj_equipment表的同时，set_time字段会更新，作为机器最近的心跳响应时间
				yjEquipmentMapper.addRecording(wxOrder.getOrderNumber(), wxOrder.getEquipment().getNumber(), orderTime);
				wxOrderMapper.setOrder(wxOrder.getOrderNumber(), "", 2, "timer", "");
				// 命令已经处理
				yjEquipmentMapper.setType(wxOrder.getEquipment().getNumber());
			}
		}
	}

	/***
	 * 检索快结束的余额开机订单，以续订
	 */
//	@Scheduled(cron = "0/10 * * * * ? ") // 每十秒运行一次
	public void getLists() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		List<WxOrder> list = wxOrderMapper.getLists(sdf.format(new Date()));
		for (WxOrder wxOrder : list) {
			// 判断是否离结束还有一分钟
			if (System.currentTimeMillis() > wxOrder.getEndTime().getTime() - (1000L * 60)) {
				Map<String, Object> maps = new HashMap<String, Object>();

				Double equipmentMoney = wxOrderMapper.getEquipmentMoney(wxOrder.getEquipment().getNumber());
				// 如果余额不足以续费，则不做处理，当订单结束时，将自然结束订单。如果余额足以续费，则进行续费一小时操作
				if (wxOrderMapper.getMoney(equipmentMoney, wxOrder.getUser().getId()) == 0) {
					continue;
				}
				logs.info(String.format("为即将结束订单%s续费", wxOrder.getOrderNumber()));
				String number = wxOrder.getOrderNumber();
				String orderNumber = Achieve.getUUIDString();
				Timestamp endTime = new Timestamp(wxOrder.getEndTime().getTime() + (1000 * 60 * 60));
				// String i = "1";
				String i = "60"; // 续费订单时长以分钟为单位，最少60分钟，即1小时
				maps.put("time", i);
				maps.put("code", "0");
				maps.put("msg", "success");
				JSONObject jsonObject = new JSONObject();
				jsonObject.put("orderNumber", number);
				maps.put("data", jsonObject);

				// 扣钱
				wxUserWalletService.setDelMoney(wxOrder.getUser().getId(), equipmentMoney,"余额开机",wxOrder.getOrderNumber());
				// 消费之后，奖励积分
				wxUserWalletService.setAddIntegration(wxOrder.getUser().getId(), equipmentMoney.intValue());
				// 增加积分明细
				WxUserIntegrationRecord wxUserIntegrationRecords = new WxUserIntegrationRecord();
				WxUser user = new WxUser();
				user.setId(wxOrder.getUser().getId());
				wxUserIntegrationRecords.setUser(user);
				wxUserIntegrationRecords.setType(0);
				wxUserIntegrationRecords.setText("消费奖励");
				wxUserIntegrationRecords.setIntegration(String.valueOf(equipmentMoney.intValue()));
				wxUserIntegrationRecordMapper.insert(wxUserIntegrationRecords);
				// 添加订单
				wxOrderMapper.addOrder(orderNumber, wxOrder.getUser().getId(), "续费充值订单", "2", "续费充值订单",
						String.valueOf(equipmentMoney), "0", wxOrder.getEquipment().getNumber(), Integer.valueOf(i),
						new Date(),endTime, equipmentMoney, "0");
				wxOrderMapper.setOrder(orderNumber, wxOrder.getEquipment().getNumber(), 4, "", "");
				// 修改订单时间
				wxOrderMapper.setEndOrderTime(endTime, Integer.valueOf(i), number, equipmentMoney);
				// 添加命令
				wxOrderMapper.addCommand(wxOrder.getEquipment().getNumber(), number,
						JSONObject.fromObject(maps).toString());

			}
		}

	}

	/***
	 * 检索快结束订单
	 */
	@Scheduled(cron = "0 0/5 * * * ?") // 每5分钟运行一次
	public void getShop() {
		Date afterDay = DateUtils.getAfterDay("-7");
		//获取一周前的订单信息
		List<WxOrder> list = wxOrderMapper.getLists(DateUtils.formatDate(afterDay));
		// logs.info("===============检测快结束订单");
		for (WxOrder wxOrder : list) {
			String number = wxOrder.getOrderNumber();
			wxOrderMapper.setOrder(number, "", 4, "", "");
			// 为代理商增加分佣和分佣记录
			// 如果orderMoney不为null的话，money和orderMoney是相等的
			logs.info("开始进入InputThread.saveAgentRecordingForAgents方法.");
			wxAgentsRecordingService.saveAgentRecordingForAgents(wxOrder.getEquipment().getNumber(), number, new Double(wxOrder.getOrderMoney()), new Double(wxOrder.getOrderMoney()));
		}

	}



}
